package main

import (
	"context"
	"strconv"
	"sync"

	"github.com/bytedance/gopkg/util/logger"
	"github.com/gin-gonic/gin"
	"github.com/tendermint/tendermint/my_test/config"
	"github.com/tendermint/tendermint/my_test/performance/entity"
	"github.com/tendermint/tendermint/my_test/performance/utils"
	"github.com/tendermint/tendermint/rpc/client/http"
)

var (
	cli *http.HTTP
	//r       *redis.Client
	//sfGroup singleflight.Group
	once sync.Once
)

func init() {
	once.Do(func() {
		var err error

		cli, err = http.New(config.DefaultIPAndPort, "/websocket")
		if err != nil {
			logger.Errorf("[New] error, err:%v", err)
			panic(err)
		}

		//r = redis.NewClient(&redis.Options{
		//	Addr:         config.RedisIPAndPort,
		//	Password:     config.RedisPassword,
		//	MinIdleConns: 2048,
		//	PoolSize:     4096,
		//	IdleTimeout:  -1,
		//})
		//if _, err = r.Ping().Result(); err != nil {
		//	logger.Errorf("[Ping] error, err:%v", err)
		//	panic(err)
		//}
		//
		//fmt.Println("Redis is OK")
		//
		//utils.PreheatWithVO(cli, r, context.TODO())
	})
}

func NewRouter() *gin.Engine {
	e := gin.New()

	group := e.Group("/query")
	{
		//group.GET("/prov", func(ctx *gin.Context) {
		//	objectId := ctx.Query("object_id")
		//
		//	result, err, _ := sfGroup.Do(ctx.Query("object_id"), func() (interface{}, error) {
		//		return r.Get(objectId).Result()
		//	})
		//
		//	if err != nil {
		//		ctx.String(200, err.Error())
		//		return
		//	}
		//
		//	ctx.String(200, result.(string))
		//})

		group.GET("/provenance", func(ctx *gin.Context) {
			// 1图片 2序列 3文本
			dataType, _ := strconv.Atoi(ctx.Query("data_type"))

			objectId := ctx.Query("object_id")

			res, err := utils.SearchTxByObjectIdAndDataType(cli, context.TODO(), objectId, dataType)
			if err != nil {
				logger.Errorf("[SearchTxByObjectIdAndDataType] error, objectId:%v, dataType:%v, err:%v", objectId, dataType, err)
				ctx.String(200, err.Error())
			}

			ctx.String(200, res)
		})

		group.POST("/verify", func(ctx *gin.Context) {
			var provRes entity.ProvResult
			if err := ctx.BindJSON(&provRes); err != nil {
				logger.Errorf("[BindJSON] error, err:%v", err)
				ctx.String(200, err.Error())
				return
			}

			if err := utils.Verify(provRes); err != nil {
				logger.Errorf("[Verify] error, err:%v", err)
				ctx.String(200, err.Error())
			}

			ctx.String(200, "verification success")
		})
	}

	return e
}

func main() {
	e := NewRouter()
	if err := e.Run(":9999"); err != nil {
		logger.Errorf("[Run] error, err:%v", err)
		panic(err)
	}
}
